import './clock.scss'
export default function (
  backgroundColor = '#333',
  fontColor = '#fff',
  dividerColor = '#333')
{
  let timer = null;
  let flips, flippers;

  // 翻转时钟类
  class Flipper {
    constructor (node, currentTime, nextTime) {
      this.isFlipping = false;
      this.duration = 600;
      this.flipNode = node;
      this.frontNode = node.find('.front');
      this.backNode = node.find('.back');
      this.setFrontTime(currentTime);
      this.setBackTime(nextTime);
    }
    setFrontTime (time) {
      this.frontNode.attr('data-num', time)
    }
    setBackTime (time) {
      this.backNode.attr('data-num', time)
    }
    flipDown (currentTime, nextTime) {
      const that = this;
      if(this.isFlipping) {
        return false;
      }
      this.isFlipping = true;
      this.setFrontTime(currentTime);
      this.setBackTime(nextTime);
      this.flipNode.addClass('running');
      setTimeout(function() {
        that.flipNode.removeClass('running');
        that.setFrontTime(nextTime);
        that.isFlipping = false;
      }, this.duration);
    };
  }

  // 获取时间字符串
  function getTimeFromDate (date) {
    return date
      .toTimeString()
      .slice(0, 8)
      .split(":")
      .join("");
  }

  // 设置定时器
  function setDigitalTimer() {
    clearInterval(timer)
    timer = setInterval(function () {
      let now =new Date();
      let nowTimeStr = getTimeFromDate(now);
      let nextTimeStr = getTimeFromDate(new Date(now.getTime() + 1000));
      flippers.forEach(function (e, i) {
        if (nowTimeStr[i] !== nextTimeStr[i]) {
          flippers[i].flipDown(nowTimeStr[i], nextTimeStr[i]);
        }
      })
    }, 1000)
  }

  // 初始化
  function init () {
    let now = new Date();
    let nowTimeStr = getTimeFromDate(new Date(now.getTime() - 1000));
    let nextTimeStr = getTimeFromDate(now);
    flips = $('.flip');
    $('.flip .digital').append(`<style>
      .digital::before, .digital::after{
        background-color: ${backgroundColor};
        color: ${fontColor};
      }
    </style>`)
    $('.divider').css({color: dividerColor})
    flippers = Array.from(flips).map(function (e, i) {
      return new Flipper($(e), nowTimeStr[i], nextTimeStr[i]);
    })
    setDigitalTimer()
  }

  init()
}
